using System;
using System.Linq;
using System.Web.Mvc;
using System.Web.WebPages;
using System.Collections.Generic;

namespace Web.Core.Extensions
{
    public class IndexedItem<TModel>
    {
        private readonly int count;
        public readonly int Index;
        public TModel Item { get; private set; }

        public string Css
        {
            get
            {
                if (Index == count - 1)
                {
                    return "last";
                }
                return ((Index%2 == 0) ? "odd" : "even");
            }
        }

        public IndexedItem(int index, TModel item, int count)
        {
            Item = item;
            Index = index;
            this.count = count;
        }
    }

    public static class RazorExtension
    {
        public static HelperResult List<T>(this IEnumerable<T> items, Func<T, HelperResult> template)
        {
            return new HelperResult(writer => {
                foreach (var item in items)
                {
                    template(item).WriteTo(writer);
                }
            });
        }

        public static HelperResult Each<TItem>(this IEnumerable<TItem> items, Func<IndexedItem<TItem>, HelperResult> template)
        {
            var temp = items.ToList();
            var count = temp.Count;
            return new HelperResult(writer => {
                var index = 0;
                var list = temp.Select(item => template(new IndexedItem<TItem>(index++, item, count)));
                foreach (var result in list)
                {
                    result.WriteTo(writer);
                }
            });
        }

        public static HelperResult RenderSection(this WebPageBase webPage, string name, Func<dynamic, HelperResult> defaultContents)
        {
            return webPage.IsSectionDefined(name) ? webPage.RenderSection(name) : defaultContents(null);
        }

        public static HtmlHelper GetPageHelper(this System.Web.WebPages.Html.HtmlHelper html)
        {
            return ((WebViewPage)WebPageContext.Current.Page).Html;
        }

    }
}